package org.wiztools.oembed;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Implementation to parse oEmbed JSON content.
 * @author subhash
 */
public class OEmbedJsonParser implements OEmbedParser {
    
    private String getInputStreamConverted(InputStream is, Charset charset) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
        StringBuilder sb = new StringBuilder();
        String str = null;
        while((str=reader.readLine()) != null) {
            sb.append(str);
        }
        return sb.toString();
    }

    /**
     * 
     * @param is The JSON content as stream.
     * @param charset The charset used to read the stream content.
     * @return The response.
     * @throws IOException When there is read error from the stream.
     * @throws OEmbedException  When there is any other error like JSON-parse error.
     */
    @Override
    public OEmbedResponse getResponse(InputStream is, Charset charset) throws IOException, OEmbedException {
        try {
            final JSONObject obj = new JSONObject(getInputStreamConverted(is, charset));
            final String[] names = JSONObject.getNames(obj);
            OEmbedResponseBuilder builder = new OEmbedResponseBuilder();
            for(final String eName: names) {
                final String eValue = obj.getString(eName);
                builder.addElement(eName, eValue);
            }
            return builder.getResponse();
        }
        catch(JSONException ex) {
            throw new OEmbedException(ex);
        }
    }
    
}
